function visLattice3D(D, n, q, center, radius, theta, M, type)
%VISLATTICE
    if D ~= 3
        error('Wrong dimension.');
    end
    markerSize = 10;
    pointMargin = 1;
    margin = [-pointMargin, (n+pointMargin)];
    Ticks = linspace(margin(1), margin(2), n+2*pointMargin+1);
    figure; hold on;
    % 1. Plot the ellipse. 
    if type == 'e'
        %plotEllipse(center, radius);
        fsurf(@(x, y) ...
            sqrt(1.0 - ((x-center(1))./radius(1)).^2 - ((y-center(2))./radius(2)).^2).*radius(3) + center(3), ...
            [margin(1) margin(2) margin(1) margin(2)], ...
            'EdgeColor', 'none', ...
            'FaceColor', [0.5 0.5 0.5], ...
            'FaceAlpha', 0.5);
        hold on;
    elseif type == 'b'
        plotCube(center, radius, theta);
        hold on;
    else
        disp('Unknown test case.');
    end
    M = reshape(M, 3, []);
    % 3. Plot the connecting segments. 
    BM = zeros(n+1, n+1, n+1);
    for i=1:size(M,2)
        BM(M(1,i)+1, M(2,i)+1, M(3,i)+1) = 1;
    end
    plotSegments(and(BM(2:end,:,:), BM(1:end-1,:,:)), 1);
    plotSegments(and(BM(:,2:end,:), BM(:,1:end-1,:)), 2);
    plotSegments(and(BM(:,:,2:end), BM(:,:,1:end-1)), 3);
    % 2. Mark the lattice. 
    plot3(M(1,:), M(2,:), M(3,:), 'ko', 'MarkerSize', markerSize, 'MarkerFaceColor', 'k');
    plot3(q(1), q(2), q(3), 'ko', 'MarkerSize', markerSize, 'MarkerFaceColor', 'w');
    % 3. Set up the view.
    axis equal;
    xlim([margin(1) margin(2)]);
    ylim([margin(1) margin(2)]);
    zlim([margin(1) margin(2)]);
    ax = gca;
    ax.XTick = Ticks;
    ax.YTick = Ticks;
    ax.ZTick = Ticks;
    grid on;
    hold off;
end

function plotSegments(BM, d)
    cl = 'k';
    lw = 2;
    ed = zeros(1, 3);
    ed(d) = 1;
    for k=1:size(BM,3)
        for j=1:size(BM,2)
            for i=1:size(BM,1)
                if BM(i,j,k)
                    c = [ [i j k]; [i j k] + ed ] - 1;
                    line(c(:,1), c(:,2), c(:,3), 'Color', cl, 'LineWidth', lw);
                end
            end
        end
    end
end

